package com.gamelife.web.service.impl;

import com.gamelife.web.domain.entity.SysMenu;
import com.gamelife.web.mapper.SysMenuMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gamelife.web.service.SysMenuService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.awt.*;
import java.util.*;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hsx
 * @since 2022-06-27
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Resource
    private SysMenuMapper sysMenuMapper;

    @Override
    public Set<String> selectPermissionByUserId(Long userId) {
        Set<SysMenu> sysMenus = sysMenuMapper.selectSysMenuListByUserId(userId);
        HashSet<String> permission = new HashSet<>();
        sysMenus.forEach(sysMenu -> permission.add(sysMenu.getPerms()));
        return permission;
    }

    @Override
    public List<SysMenu> selectSysMenuListByUserId(Long userId) {
        Set<SysMenu> sysMenus = sysMenuMapper.selectSysMenuListByUserId(userId);
        return new ArrayList<>(sysMenus);
    }

    @Override
    public List<SysMenu> buildSysMenuTree(List<SysMenu> menus) {
        // 查询出一级菜单  parentId == 0
        List<SysMenu> levelOneMenus = menus.stream()
                .filter(sysMenu -> sysMenu.getParentId() == 0)
                .sorted(Comparator.comparingInt(SysMenu::getOrderNum))
                .collect(Collectors.toList());
        // 递归查询子菜单
        levelOneMenus.forEach(item -> {
            item.setChildren(getChildren(item, menus));
        });

        // // 打印树结构
        // levelOneMenus.forEach(item -> {
        //     System.out.println(item.getName());
        //     item.getChildren().forEach(item2 -> {
        //         System.out.print("--");
        //         System.out.println(item2.getName());
        //         item2.getChildren().forEach(item3 -> {
        //             System.out.print("----");
        //             System.out.println(item3.getName());
        //         });
        //     });
        // });
        return levelOneMenus;
    }

    /**
     * 获取菜单一个节点的所有子节点组成的树状列表
     *
     * @param root 父节点
     * @param all  全部的菜单列表
     * @return 树状的菜单结构
     */
    private List<SysMenu> getChildren(SysMenu root, List<SysMenu> all) {
        return all.stream()
                .filter(item -> item.getParentId().equals(root.getId()))
                .peek(item -> item.setChildren(getChildren(item, all)))
                .sorted(Comparator.comparingInt(SysMenu::getOrderNum))
                .collect(Collectors.toList());
    }
}
